/**
给你单链表的头节点 head ，请你反转链表，并返回反转后的链表。
输入：head = [1,2,3,4,5]
输出：[5,4,3,2,1]
 */
// 链表节点定义
function ListNode(val, next) {
  this.val = (val === undefined ? 0 : val)
  this.next = (next === undefined ? null : next)
}

function reverseList(head) {
  let pre = null;
  let curr = head;
  while(curr) {
    let temp = curr.next;
    curr.next = pre;
    pre = curr;
    curr = temp
  }
  return pre
}

// 辅助函数：数组转链表
function arrayToList(arr) {
  return arr.reduceRight((pre, curr) => new ListNode(curr, pre), null)
}

// 辅助函数：链表转数组（用于验证结果）
function listToArray(head) {
  const arr = []
  let curr = head
  while (curr) {
    arr.push(curr.val)
    curr = curr.next
  }
  return arr
}

const head = arrayToList([1,2,3,4,5])
const result = reverseList(head)
console.log(listToArray(result))
